package com.sskj.xgja.api;

import android.accounts.NetworkErrorException;

import com.google.gson.JsonSyntaxException;
import com.hjq.toast.ToastUtils;
import com.sskj.xgja.BasePresenter;
import com.sskj.base.api.OtherLoginEvent;
import com.sskj.base.api.OtherLoginException;

import org.greenrobot.eventbus.EventBus;

import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class ApiObserver<T> implements Observer<HttpResponse<T>> {

    private BasePresenter mPresenter;

    private boolean showLoading;


    public ApiObserver(BasePresenter presenter) {
        mPresenter = presenter;
    }

    public ApiObserver(BasePresenter presenter, boolean showLoading) {
        mPresenter = presenter;
        this.showLoading = showLoading;
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (mPresenter != null) {
            if (showLoading && mPresenter.mView != null) {
                mPresenter.mView.showLoading();
            }
            mPresenter.addRequest(d);
        }
    }

    @Override
    public void onNext(HttpResponse<T> result) {
        if (mPresenter != null && mPresenter.mView != null) {
            onComplete();
            if (result.getStatus() == 200) {
                onSuccess(result.getData());
            } else {
                onError(new ServiceException(result, result.getMsg()));
            }
        }
    }


    @Override
    public void onError(Throwable e) {
        onComplete();
        if (e instanceof NetworkErrorException) {
            e.printStackTrace();
        } else if (e instanceof JsonSyntaxException) {
            e.printStackTrace();
        } else if (e instanceof SocketTimeoutException) {
            ToastUtils.show("网络连接超时，请重试");
        } else if (e instanceof OtherLoginException) {
            EventBus.getDefault().post(new OtherLoginEvent());
        } else if (e instanceof ServiceException) {
            if (((ServiceException) e).getResponse().getStatus() == 505) {
            } else {
                ToastUtils.show(((ServiceException) e).getMsg());
            }
            e.printStackTrace();
        } else {
            e.printStackTrace();
        }
    }

    @Override
    public void onComplete() {
        if (mPresenter != null && mPresenter.mView != null) {
            if (showLoading) {
                mPresenter.mView.hideLoading();
            }
        }
        mPresenter = null;
    }


    public abstract void onSuccess(T data);
}
